<?php

namespace App\Http\Middleware;

use Closure;
use Auth, Cache;

class GetMenu
{
    /**
     * 需要在左边菜单栏展示的菜单后缀列表
     *
     * @var array
     */
    private $menu_show_suffix_list = [
        'list',
        'manager',
    ];

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //view()->share('comData',$this->getMenu());
        $request->attributes->set('comData_menu', $this->getMenu());
        return $next($request);
    }

    /**
     * 获取左边菜单栏
     * @return array
     */
    function getMenu()
    {
        $open_arr = [];
        $data = [];
        $data['top'] = [];
        //查找并拼接出地址的别名值
        $path_arr = explode('/', \URL::getRequest()->path());
        $url_path = '';
        $path_count = count($path_arr);
        for ($i = 0; $i < ($path_count - 1); $i++) {
            $url_path .= $path_arr[$i] . '.';
        }

        if (in_array($path_arr[($path_count - 1)], $this->menu_show_suffix_list)) {
            $url_path .= $path_arr[$path_count - 1];
        } else {
            $url_path .= 'index';
        }

        //查找出所有的地址
        $table = Cache::store('file')->rememberForever('menus', function () {
            return \App\Models\Admin\Permission::where(function ($query) {
                foreach ($this->menu_show_suffix_list as $suffix) {
                    $like = '%' . $suffix;
                    $query->orWhere('name', 'LIKE', $like);
                }
            })->orWhere('name', 'LIKE', '%index')
                ->orWhere('cid', 0)
                ->get();
        });

        foreach ($table as $v) {
            if ($v->cid == 0 || \Gate::forUser(auth('admin')->user())->check($v->name)) {
                if ($v->name == $url_path) {
                    $open_arr[] = $v->id;
                    $open_arr[] = $v->cid;
                }
                $data[$v->cid][] = $v->toarray();
            }
        }
        foreach ($data[0] as $v) {
            if (isset($data[$v['id']]) && is_array($data[$v['id']]) && count($data[$v['id']]) > 0) {
                $data['top'][] = $v;
            }
        }
        unset($data[0]);
        //ation open 可以在函数中计算给他
        $data['openarr'] = array_unique($open_arr);
        return $data;

    }
}
